7. 数猫をGUIアプリにする(3)
https://gyazo.com/9369fc3389fc243b90b073d5e608447d
SuunekoCanvasクラスのオブジェクトに、数猫を楽しむための最低限の機能を付け加えます。
code: suuneko.py
from tkinter import Frame, Button
from suunekocanvas import SuunekoCanvas
class Suuneko(SuunekoCanvas):
UNDO = []
REDO = []
def __init__(self, CellSize = 60):
super(Suuneko, self).__init__(CellSize)
self.base11 = Frame(self.base1)
self.base11.pack()
self.base111 = Frame(self.base11)
self.base111.pack()
self.eraseButton = Button(self.base111, text = ' fill ', command = self.fill)
self.eraseButton.pack(side="left")
self.eraseButton = Button(self.base111, text = ' remove ', command = self.remove)
self.eraseButton.pack(side="left")
self.eraseButton = Button(self.base111, text = ' <<< ', command = self.undo)
self.eraseButton.pack(side="left")
self.eraseButton = Button(self.base111, text = ' >>> ', command = self.redo)
self.eraseButton.pack(side="left")
self.eraseButton = Button(self.base111, text = ' clear ', command = self.clear)
self.eraseButton.pack(side="left")
self.eraseButton = Button(self.base111, text = ' save ', command = self.save)
self.eraseButton.pack(side="left")
def get_red_numbers(self, i, j):
N = []
for n in range(1, 10):
if self.get_color(i, j, n) == 'red':
N.append(n)
return N
def fill(self):
todo = []
for i in range(9):
for j in range(9):
if self.is_blank(i, j):
N = self.get_red_numbers(i, j);
if len(N) == 1:
todo.append(('fix', i, j, N0)) self.do(todo)
def remove(self):
TODO = []
for i in range(9):
for j in range(9):
if self.is_blank(i, j):
for n in self.get_red_numbers(i, j):
TODO.append(('change_color', i, j, n, c))
self.do(TODO)
def do(self, TODO):
for cmd in TODO:
if f == 'fix':
self.fix(*args)
elif f == 'change_color':
self.change_color(*args)
else:
return
self.UNDO.append(TODO)
def undo(self):
if self.UNDO == []:
return
TODO = self.UNDO.pop()
for cmd in TODO:
if f == 'fix':
i, j, n = args
self.change_number(i, j, 0)
self.hide(i, j, 0)
for n in range(1, 10):
self.reveal(i, j, n)
elif f == 'change_color':
i, j, n, c = args
self.change_color(i, j, n, 'red')
else:
return
self.REDO.append(TODO)
def redo(self):
if self.REDO == []:
return
TODO = self.REDO.pop()
self.do(TODO)
def clear(self):
for i in range(9):
for j in range(9):
if self.is_blank(i, j):
for n in range(1, 10):
if self.get_color(i, j, n) == 'red':
self.change_color(i, j, n, 'grey50')
else:
if self.get_color(i, j, 0) == 'red':
self.change_color(i, j, 0, 'black')
def save(self):
for i in range(9):
for j in range(9):
n = self.get_number(i, j)
with open('save.py', 'w') as fd:
fd.write('A = %s\n' % A)
if __name__ == "__main__":
suuneko = Suuneko()
for i in range(9):
for j in range(9):
if n:
suuneko.change_status(i, j, n)
suuneko.fill()
suuneko.run()